package cn.edu.cuc.yjsy.admin.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
import org.eclipse.emf.ecore.xmi.XMIResource;
import org.eclipse.emf.ecore.xmi.impl.XMIResourceFactoryImpl;

import cn.edu.cuc.yjsy.model.*;
import cn.edu.cuc.yjsy.database.Database;
import cn.edu.cuc.yjsy.database.DatabaseFactory;
import cn.edu.cuc.yjsy.database.DatabasePackage;
import cn.edu.cuc.yjsy.database.Field;
import cn.edu.cuc.yjsy.database.Table;

public class GenerateDatabase {
	public static void main(String[] args) {
		// Create a resource set to hold the resources.
		//
		ResourceSet resourceSet = new ResourceSetImpl();
		
		// Register the appropriate resource factory to handle all file extentions.
		//
		resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put
			(Resource.Factory.Registry.DEFAULT_EXTENSION, 
			 new XMIResourceFactoryImpl());

		// Register the package to ensure it is available during loading.
		//
		resourceSet.getPackageRegistry().put
			(DatabasePackage.eNS_URI, 
			 DatabasePackage.eINSTANCE);
        
		try {
			Resource resource = resourceSet.createResource(URI.createURI("http:///My.database"));
			Database db = DatabaseFactory.eINSTANCE.createDatabase();
			db.setName("YJSY admin system");
			db.setDriver("sun.jdbc.odbc.JdbcOdbcDriver");
			db.setUrl("jdbc:odbc:driver={Microsoft Excel Driver (*.xls)};DBQ=v:\\sampleData.xls");
			Table student = DatabaseFactory.eINSTANCE.createTable();
			student.setName("student");
			student.setTableName("[TableA$]");
			for(int i = 0; i < ModelPackage.STUDENT_FEATURE_COUNT; i++){
				Field field = DatabaseFactory.eINSTANCE.createField();
				String fieldName = StudentAttributes.getAttributeName(i);
				field.setName(fieldName);
				field.setFieldName(fieldName);
				student.getField().add(field);
			}
			db.getTable().add(student);
			resource.getContents().add(db);
			File file = new File("db.xml");
			Map options = new HashMap();
			options.put(XMIResource.OPTION_DECLARE_XML, Boolean.TRUE);
			options.put(XMIResource.OPTION_ENCODING, "UTF-8");
			resource.save(new FileOutputStream(file), options);
//			resource.save(System.out, null);
		}
		catch (IOException exception) {
			exception.printStackTrace();
		}
	}
}
